# -*-coding: utf-8 -*-
"""
    @Theme   : Questions and Answers
    @Time    : 2024/7/10 14:16
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from datetime import datetime

from flask import Blueprint, render_template, jsonify, request, g, current_app

from qanda.utils import check_answer_valid, check_question_valid, check_vote, login_required
from qanda.models_business import db_utils

qaa_bp = Blueprint('qaa', __name__)


@qaa_bp.route('/')
@qaa_bp.route('/page/<int:page>')
def index(page=1):
    page_total_question = current_app.config['QUESTION_PER_PAGE']
    start = (page - 1) * page_total_question if page >= 1 else 0

    question_id_score_list = db_utils.redis.get_doc_rank_range('question', start, page_total_question)
    question_list, total_question = db_utils.mongo.query_question(question_id_score_list)

    total_page = total_question // page_total_question + (1 if total_question % page_total_question > 0 else 0)
    session_data = db_utils.redis.fetch_session(request.cookies.get('session_id'))
    return render_template('index.html', question_list=question_list,
                           session=session_data, current_page=page, page_list=list(range(1, total_page+1)))


@qaa_bp.route('/question/<question_id>')
@qaa_bp.route('/question/<question_id>/page/<int:page>')
def question_detail(question_id, page=1):
    page_total_answer = current_app.config['QUESTION_ANSWER_PER_PAGE']
    start = (page - 1) * page_total_answer if page >= 1 else 0

    answer_id_score_list = db_utils.redis.get_doc_rank_range('answer', start, page_total_answer, question_id=question_id)
    question_answer_dict = db_utils.mongo.query_answer(question_id, answer_id_score_list)

    session_data = db_utils.redis.fetch_session(request.cookies.get('session_id'))
    could_answer_this_question = True
    if 'user' not in session_data or db_utils.redis.check_user_answer_question(session_data['user'], question_id):
        could_answer_this_question = False

    total_answer = question_answer_dict['answer_num']
    total_page = total_answer // page_total_answer + (1 if total_answer % page_total_answer > 0 else 0)
    session_data['could_answer_this_question'] = could_answer_this_question
    return render_template('answer_list.html', question_answer_dict=question_answer_dict,
                           session=session_data, current_page=page, page_list=list(range(1, total_page+1)))


@qaa_bp.route('/post_answer', methods=['POST'])
@login_required
def post_answer():
    answer = request.json
    is_valid = check_answer_valid(answer)

    if not is_valid['success']:
        return jsonify(is_valid)

    question_id = answer['question_id']
    author = g.user_session['user']

    if db_utils.redis.check_user_answer_question(author, question_id):
        return jsonify({'success': False, 'reason': '已经回答过这个问题，不能回答两次。'})

    answer_id = db_utils.mongo.insert_answer(question_id, answer['answer'], author, datetime.now())
    db_utils.redis.add_answer_vote_set(question_id, answer_id)
    db_utils.redis.set_answer_flag(question_id, author)
    return jsonify({'success': True})


@qaa_bp.route('/post_question', methods=['POST'])
@login_required
def post_question():
    question = request.json
    is_valid = check_question_valid(question)

    if not is_valid['success']:
        return jsonify(is_valid)

    author = g.user_session['user']
    doc_id = db_utils.mongo.insert_question(question['title'], question['detail'], author, datetime.now())
    db_utils.redis.add_question_vote_set(doc_id)
    return jsonify({'success': True, 'doc_id': doc_id})


@qaa_bp.route('/vote', methods=['POST'])
@login_required
def vote():
    vote_data = request.json

    is_valid = check_vote(vote_data)
    if not is_valid['success']:
        return jsonify(is_valid)

    try:
        db_utils.redis.increase_vote_score(vote_data, g.user_session['user'])
    except RuntimeError as e:
        return jsonify({'success': False, 'reason': str(e)})
    else:
        value = 1 if vote_data['value'] == 'vote_up' else -1
        db_utils.mongo.do_vote(
            vote_data['doc_type'],
            vote_data['doc_id'],
            value,
            g.user_session['user'],
            datetime.now()
        )
        return jsonify({'success': True})


def update_question(info):
    if 'doc_id' not in info or 'title' not in info or 'text' not in info:
        return {'success': False, 'reason': '字段不全，必要字段：doc_id, title, text'}
    db_utils.mongo.update_question(info['doc_id'], info['title'], info['text'])
    return {'success': True}


def update_answer(info):
    if 'doc_id' not in info or 'text' not in info:
        return {'success': False, 'reason': '字段不全，必要字段：doc_id, text'}
    db_utils.mongo.update_answer(info['doc_id'], info['text'])
    return {'success': True}


@qaa_bp.route('/update', methods=['POST'])
@login_required
def update():
    info = request.json
    update_type = info.get('update_type')
    if update_type == 'question':
        return jsonify(update_question(info))
    elif update_type == 'answer':
        return jsonify(update_answer(info))
    else:
        return jsonify({'success': False, 'reason': 'update_type只能是 question 或者answer'})
